<?php

    class SocialController extends Zend_Controller_Action
    {

        public function init()
        {
            /* Initialize action controller here */
        }

        public function indexAction()
        {
            
        }

        public function loginwithfacebookAction()
        {
            // Create our Application instance (replace this with your appId and secret).
            $facebook = new Facebook(array(
                'appId' => FACEBOOK_APP_ID,
                'secret' => FACEBOOK_SECRET_ID,
            ));

            // Get User ID
            $user = $facebook->getUser();

            // We may or may not have this data based on whether the user is logged in.
            //
            // If we have a $user id here, it means we know the user is logged into
            // Facebook, but we don't know if the access token is valid. An access
            // token is invalid if the user logged out of Facebook.

            if ($user)
            {
                try
                {
                    // Proceed knowing you have a logged in user who's authenticated.
                    $user_profile = $facebook->api('/me');

//                    prd($user_profile);
                    $model = new Application_Model_Common();
                    //record exists
                    $check_username = $model->getdata(TABLE_USERS, "user_username = '" . $user_profile["username"] . "'");
                    $check_email = $model->getdata(TABLE_USERS, "user_email = '" . $user_profile["email"] . "'");
                    $record = $model->getdata(TABLE_USERS, "user_facebook_id = '" . $user_profile["id"] . "'");
                    if (!empty($record))
                    {
                        $user_id = $record["user_id"];
                    }

                    if (!empty($check_email))
                    {
                        //this email already exists
                        $update_data_array = array(
                            "user_facebook_id" => $user_profile["id"],
                            "facebook_username" => $user_profile["username"]
                        );
                        $model->updateRecordData($update_data_array, "user_email = '" . $user_profile["email"] . "'", TABLE_USERS);

                        if (empty($check_email["user_username"]))
                        {
                            $update_data_array = array(
                                "user_username" => $user_profile["username"]
                            );
                            $model->updateRecordData($update_data_array, "user_email = '" . $user_profile["email"] . "'", TABLE_USERS);
                        }

                        $_SESSION["messageSuccess"] = "Facebook account has been connected";

                        $user_id = $check_email["user_id"];
                    }
                    else if (!empty($check_username))
                    {
                        //this email already exists
                        $update_data_array = array(
                            "user_facebook_id" => $user_profile["id"],
                            "facebook_username" => $user_profile["username"]
                        );
                        $model->updateRecordData($update_data_array, "user_username = '" . $user_profile["username"] . "'", TABLE_USERS);

                        if (empty($check_email))
                        {
                            $update_data_array = array(
                                "user_email" => $user_profile["email"]
                            );
                            $model->updateRecordData($update_data_array, "user_email = '" . $user_profile["email"] . "'", TABLE_USERS);
                        }

                        $_SESSION["messageSuccess"] = "Facebook account has been connected";

                        $user_id = $check_email["user_id"];
                    }
                    else if (empty($check_email) && empty($check_username) && empty($record))
                    {
                        //insert record

                        $insert_data_array = array(
                            "user_first_name" => $user_profile["first_name"],
                            "user_last_name" => $user_profile["last_name"],
                            "user_username" => $user_profile["username"],
                            "user_email" => $user_profile["email"],
                            "facebook_username" => $user_profile["username"],
                            "user_active" => "1",
                            "user_facebook_id" => $user_profile["id"],
                            "user_ipaddress" => $_SERVER["REMOTE_ADDR"],
                        );
                        $model->insertRecordData($insert_data_array, TABLE_USERS);
                        $user_id = $model->getLastInsertId(TABLE_USERS);

                        $_SESSION["messageSuccess"] = "Please complete your account details";
                    }
                    $dbAdapter = Zend_Db_Table::getDefaultAdapter();
                    $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

                    $authAdapter->setTableName(TABLE_USERS)
                            ->setIdentityColumn('user_id')
                            ->setCredentialColumn('user_facebook_id');

                    $authAdapter->setIdentity($user_id)
                            ->setCredential($user_profile["id"]);

                    $zend_auth = Zend_Auth::getInstance();
                    $zend_auth->setStorage(new Zend_Auth_Storage_Session('User_Auth'));
                    $result = $zend_auth->authenticate($authAdapter);

                    if ($result->isValid())
                    {
                        $user = $authAdapter->getResultRowObject(null, 'user_password');
                        $zend_auth->getStorage()->write($user);
                    }
                    else
                    {
                        $_SESSION["messageError"] = "Error occured, please try again.";
                        $this->redirect("index");
                    }
                    $this->redirect("profile");
                }
                catch (FacebookApiException $e)
                {
                    error_log($e);
                    $user = null;
                }
            }
            else
            {
                $this->redirect("profile");
            }
        }

        public function loginwithtwitterAction()
        {
            // use the user's previously stored temporary credentials here
            $twitter = new TwitterOAuth(TWITTER_APP_ID, TWITTER_SECRET_ID, $_SESSION["oauth_token"], $_SESSION["oauth_token_secret"]);

            // uses the oauth_token (from the request) already.
            // you store these credentials in your database (see below).
            $credentials = $twitter->getAccessToken($_REQUEST["oauth_verifier"]);

            unset($_SESSION["oauth_token"]);
            unset($_SESSION["oauth_token_secret"]);

//            prd($credentials);
            if (isset($credentials["Invalid request token"]))
            {
                $_SESSION["messageError"] = "Invalid request token. Please try again.";
                $this->redirect("index");
            }

            $twitter_id = $credentials["user_id"];
            $twitter_username = $credentials["screen_name"];

            $model = new Application_Model_Common();
            //record exists
            $check_username = $model->getdata(TABLE_USERS, "user_username = '" . $twitter_username . "'");
            $record = $model->getdata(TABLE_USERS, "user_twitter_id = '" . $twitter_id . "'");

            if (!empty($record))
            {
                $user_id = $record["user_id"];
            }
            else if (!empty($check_username))
            {
                //this email already exists
                $update_data_array = array(
                    "user_twitter_id" => $twitter_id,
                    "twitter_username" => $twitter_username
                );
                $model->updateRecordData($update_data_array, "user_username= '" . $twitter_username . "'", TABLE_USERS);

                $_SESSION["messageSuccess"] = "Twitter account has been connected";

                $user_id = $check_username["user_id"];
            }
            else if (empty($check_username) && empty($record))
            {
                //insert record

                $insert_data_array = array(
                    "user_first_name" => $twitter_username,
                    "user_username" => $twitter_username,
                    "twitter_username" => $twitter_username,
                    "user_active" => "1",
                    "user_twitter_id" => $twitter_id,
                    "user_ipaddress" => $_SERVER["REMOTE_ADDR"],
                );
//                prd($insert_data_array);
                $model->insertRecordData($insert_data_array, TABLE_USERS);

                $user_id = $model->getLastInsertId(TABLE_USERS);

                $_SESSION["messageSuccess"] = "Please complete your account details";
            }

            $dbAdapter = Zend_Db_Table::getDefaultAdapter();
            $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

            $authAdapter->setTableName(TABLE_USERS)
                    ->setIdentityColumn('user_id')
                    ->setCredentialColumn('user_twitter_id');

            $authAdapter->setIdentity($user_id)
                    ->setCredential($twitter_id);

            $zend_auth = Zend_Auth::getInstance();
            $zend_auth->setStorage(new Zend_Auth_Storage_Session('User_Auth'));
            $result = $zend_auth->authenticate($authAdapter);

            if ($result->isValid())
            {
                $user = $authAdapter->getResultRowObject(null, 'user_password');
                $zend_auth->getStorage()->write($user);
                $_SESSION["messageSuccess"] = "You are logged in with twitter";
            }
            else
            {
                $_SESSION["messageError"] = "Error occured, please try again.";
                $this->redirect("index");
            }
            $this->redirect("profile");
        }

        public function loginwithlinkedinAction()
        {

            getAccessToken();

            function fetch($method, $resource, $body = '')
            {
                $params = array('oauth2_access_token' => $_SESSION['access_token'],
                    'format' => 'json',
                );

                // Need to use HTTPS
                $url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
                // Tell streams to make a (GET, POST, PUT, or DELETE) request
                $context = stream_context_create(
                        array('http' =>
                            array('method' => $method,
                            )
                        )
                );

                // Hocus Pocus
                $response = file_get_contents($url, false, $context);

                // Native PHP object, please
                return json_decode($response);
            }

            $user = fetch('GET', '/v1/people/~:(id,firstName,lastName,email-address)');
            if (isset($_GET['code']) && isset($_GET['state']))
            {
                $first_name = $user->firstName;
                $last_name = $user->lastName;
                $email = $user->emailAddress;
                $linkedin_id = $user->id;
//                prd($user);

                $model = new Application_Model_Common();
                //record exists
                $check_username = $model->getdata(TABLE_USERS, "user_username = '" . $email . "'");
                $check_email = $model->getdata(TABLE_USERS, "user_email = '" . $email . "'");
                $record = $model->getdata(TABLE_USERS, "user_linkedin_id = '" . $linkedin_id . "'");
                if (!empty($check_email))
                {
                    //this email already exists
                    $update_data_array = array(
                        "user_linkedin_id" => $linkedin_id,
                        "linkedin_username" => $email
                    );
                    $model->updateRecordData($update_data_array, "user_email = '" . $email . "'", TABLE_USERS);

                    if (empty($check_email["user_username"]))
                    {
                        $update_data_array = array(
                            "user_username" => $email
                        );
                        $model->updateRecordData($update_data_array, "user_email = '" . $email . "'", TABLE_USERS);
                    }

                    $_SESSION["messageSuccess"] = "LinkedIn account has been connected";

                    $user_id = $check_email["user_id"];
                }
                else if (!empty($check_username))
                {
                    //this email already exists
                    $update_data_array = array(
                        "user_linkedin_id" => $linkedin_id,
                        "linkedin_username" => $email
                    );
                    $model->updateRecordData($update_data_array, "user_username = '" . $email . "'", TABLE_USERS);

                    if (empty($check_email))
                    {
                        $update_data_array = array(
                            "user_email" => $email
                        );
                        $model->updateRecordData($update_data_array, "user_email = '" . $email . "'", TABLE_USERS);
                    }

                    $_SESSION["messageSuccess"] = "LinkedIn account has been connected";

                    $user_id = $check_email["user_id"];
                }
                else if (empty($check_email) && empty($check_username) && empty($record))
                {
                    //insert record

                    $insert_data_array = array(
                        "user_first_name" => $first_name,
                        "user_last_name" => $last_name,
                        "user_username" => $email,
                        "user_email" => $email,
                        "linkedin_username" => $email,
                        "user_active" => "1",
                        "user_linkedin_id" => $linkedin_id,
                        "user_ipaddress" => $_SERVER["REMOTE_ADDR"],
                    );
                    $model->insertRecordData($insert_data_array, TABLE_USERS);
                    $user_id = $model->getLastInsertId(TABLE_USERS);

                    $_SESSION["messageSuccess"] = "Please complete your account details";
                }
                $dbAdapter = Zend_Db_Table::getDefaultAdapter();
                $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

                $authAdapter->setTableName(TABLE_USERS)
                        ->setIdentityColumn('user_id')
                        ->setCredentialColumn('user_linkedin_id');

                $authAdapter->setIdentity($user_id)
                        ->setCredential($linkedin_id);

                $zend_auth = Zend_Auth::getInstance();
                $zend_auth->setStorage(new Zend_Auth_Storage_Session('User_Auth'));
                $result = $zend_auth->authenticate($authAdapter);

                if ($result->isValid())
                {
                    $user = $authAdapter->getResultRowObject(null, 'user_password');
                    $zend_auth->getStorage()->write($user);
                }
                else
                {
                    $_SESSION["messageError"] = "Error occured, please try again.";
                    $this->redirect("index");
                }
                $this->redirect("profile");
            }
            else
            {
                $this->redirect("profile");
            }
        }

    }

    